package com.ndp.fb.walle.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ndp.ec.core.UserService;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.connectionobject.ConnectionObjectType;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.model.AdResourceComment;
import com.ndp.fb.model.AdResourceStats;
import com.ndp.fb.rdb.api.ProductManageRdbService;
import com.ndp.fb.rdb.model.ConnectionObject;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.productmanage.ProductManage;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.util.StringUtil;
import com.ndp.fb.walle.business.AdImageService;
import com.ndp.fb.walle.business.AdResourceService;
import com.ndp.fb.walle.business.AdVideoService;
import com.ndp.fb.walle.business.ConnectionObjectService;
import com.ndp.fb.walle.model.bo.adresource.AdVideoBo;
import com.ndp.fb.walle.model.bo.adresource.result.UploadAdimageBoResult;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.adresource.AdResourceCommentParam;
import com.ndp.fb.walle.model.vo.adresource.AdResourceQueryParam;
import com.ndp.fb.walle.model.vo.adresource.AdResourceUpdateParam;
import com.ndp.fb.walle.model.vo.adresource.AdimageInitParam;
import com.ndp.fb.walle.model.vo.adresource.AdimageTagParam;
import com.ndp.fb.walle.model.vo.adresourcestats.param.AdResourceStatsParam;
import com.ndp.fb.walle.util.ResponseUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by yeahmobi on 2015/3/19.
 */
@RequestMapping("/adresource")
@Controller
public class AdResourceController {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private AdResourceService adResourceService;

    @Autowired
    private AdImageService adImageService;

    @Reference
    private UserService userService;

    @Autowired
    private ConnectionObjectService connectionObjectService;

    @Reference
    private ProductManageRdbService productManageRdbService;

    @Autowired
    private AdVideoService adVideoService;

    /**
     * 删除图片
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "deleteAdImages")
    @ResponseBody
    public ResponseEntity<String> deleteAdImages(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        try {
            JSONObject jsonObject = JSON.parseObject(param);
            String mongodbIds = jsonObject.getString("mongodbIds");
            if (StringUtils.isNoneEmpty(mongodbIds)) {
                Iterable<String> mongodbIds1 = Splitter.on("|").omitEmptyStrings().trimResults().split(mongodbIds);
                List<String> strings = Lists.newArrayList(mongodbIds1);
                User user = (User) request.getSession().getAttribute("user");
                adImageService.deleteAdImages(user.getTicket(), strings);
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, "");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 根据mongoId查询图片，用于编辑、查看等
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getAdimagesById")
    @ResponseBody
    public ResponseEntity<String> getAdimagesById(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {
            JSONObject jsonObject = JSON.parseObject(param);
            String mongodId = jsonObject.getString("mongodId");
            User user = (User) request.getSession().getAttribute("user");
            //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
            AdResourceStats adImageBymongodId = adImageService.getAdImageBymongodId(mongodId);
            Iterator<String> it = adImageBymongodId.getUserIdSet().iterator();
            if (it.hasNext()) {
                String uploader = it.next();
                if (uploader != null && !uploader.equals(user.getTicket())) {
                    adImageService.updateCountPageView(user.getTicket(), mongodId, adImageBymongodId.getNumOfPageViews(), adImageBymongodId.getPeopleNumOfPageViews());
                }
            }

            data = adResourceStatsToMap(adImageBymongodId, null, null);
            if (adImageBymongodId.getUserIdSet() != null && adImageBymongodId.getUserIdSet().size() > 0) {
                String userId = adImageBymongodId.getUserIdSet().iterator().next();
                User userByTicket = userService.getUserByTicket(userId);
                if (userByTicket == null) {
                    data.put("uploadUserName", "账号已经被删除");
                } else {
                    data.put("uploadUserName", userByTicket.getNickname());
                }

            }

        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 根据mongoid获取图片评论
     * @param param
     * @return
     */
    @RequestMapping(value = "getCommentsById")
    @ResponseBody
    public ResponseEntity<String> getCommentsById(@RequestParam(value = "param", required = true) String param) {
        ErrorType errorType = null;
        AdResourceStats data = null;
        try {
            JSONObject jsonObject = JSON.parseObject(param);
            String mongodId = jsonObject.getString("mongodId");
            data = adImageService.getAdImageBymongodId(mongodId);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    private Map<String, Object> adResourceStatsToMap(AdResourceStats adImageBymongodId, List<User> userList, Map<String, Integer> activeAdCountMap) {
        Map data = null;
        try {
            data = BeanUtils.describe(adImageBymongodId);
            data.remove("tags");
        } catch (Exception e) {
            logger.error("xxxxxxxx", e);
            data = new HashMap<>();
        }
        Map<String, List<Object>> tags = adImageBymongodId.getTags();
        if (tags != null) {
            data.put("appNames", tags.get("application"));
            data.put("countries", tags.get("countries"));
            data.put("languages", tags.get("languages"));
            data.put("interests", tags.get("interests"));
            data.put("tags", tags.get("custom"));
            data.put("id", adImageBymongodId.getMongodbId());

            if (tags.containsKey("gender") && tags.get("gender").size() > 0) {
                data.put("gender", tags.get("gender").get(0));
            }
        }

        String reviewer = adImageBymongodId.getReviewer();
        Set<String> userIdSet = adImageBymongodId.getUserIdSet();
        if (userIdSet != null && userIdSet.size() > 0 && ListUtil.isNotEmpty(userList)) {
            String next = userIdSet.iterator().next();
            for (User user : userList) {
                if (StringUtils.isNoneEmpty(next) && next.equals(user.getTicket())) {
                    data.put("uploadUserName", user.getNickname() + (StringUtil.isEmpty(reviewer) ? " " : "（第三方）"));
                    break;
                }
            }
        }
        // 设置当前激活状态的广告数量
        if (!CollectionUtils.isEmpty(activeAdCountMap)) {
            Integer adCount = activeAdCountMap.get(adImageBymongodId.getImageHash());
            if (null == adCount) {
                adCount = 0;
            }
            data.put("adCount", adCount);
        } else {
            data.put("adCount", 0);
        }
        return data;
    }

    private Map<String, Object> adResourceStatsToMapForReview(AdResourceStats adImageBymongodId, List<User> userList, Map<String, Integer> activeAdCountMap) {
        Map data = null;
        try {
            data = BeanUtils.describe(adImageBymongodId);
            data.remove("tags");
        } catch (Exception e) {
            logger.error("xxxxxxxx", e);
            data = new HashMap<>();
        }
        Map<String, List<Object>> tags = adImageBymongodId.getTags();
        if (tags != null) {
            data.put("appNames", tags.get("application"));
            data.put("countries", tags.get("countries"));
            data.put("languages", tags.get("languages"));
            data.put("interests", tags.get("interests"));
            data.put("tags", tags.get("custom"));
            data.put("id", adImageBymongodId.getMongodbId());

            if (tags.containsKey("gender") && tags.get("gender").size() > 0) {
                data.put("gender", tags.get("gender").get(0));
            }
        }

        String reviewer = adImageBymongodId.getReviewer();
        Set<String> userIdSet = adImageBymongodId.getUserIdSet();
        if (userIdSet != null && userIdSet.size() > 0 && ListUtil.isNotEmpty(userList)) {
            String next = userIdSet.iterator().next();
            for (User user : userList) {
                if (StringUtils.isNoneEmpty(next) && next.equals(user.getTicket())) {
                    data.put("uploadUserName", user.getNickname());
                    break;
                }
            }
        }
        // 设置当前激活状态的广告数量
        if (!CollectionUtils.isEmpty(activeAdCountMap)) {
            Integer adCount = activeAdCountMap.get(adImageBymongodId.getImageHash());
            if (null == adCount) {
                adCount = 0;
            }
            data.put("adCount", adCount);
        } else {
            data.put("adCount", 0);
        }
        return data;
    }

    /**
     * 素材管理-根据条件查询图片列表
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getAdimagesList")
    @ResponseBody
    public ResponseEntity<String> getAdimagesList(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {

            AdimageTagParam adimageTagParam = JSON.parseObject(param, AdimageTagParam.class);
            User user = (User) request.getSession().getAttribute("user");

            if (adimageTagParam.getPSize() == null) {
                adimageTagParam.setPSize(CommonConstants.DEFAULT_PAGE_SIZE_100);
            }

            if (adimageTagParam.getCPage() == null) {
                adimageTagParam.setCPage(1);
            }

            //外部美宣查询只能查询自己的, 增加有权限的应用
            changeAdResourceTagParams(adimageTagParam, user);

            //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
            Map<String, Object> groupByImageHashResult = adImageService.getAdimagesList(adimageTagParam, user);
            if (null == groupByImageHashResult || null == groupByImageHashResult.get("adResourceStatsList")) {
                data = new HashMap<>();
                data.put("resources", "");
                data.put("summary","");
            } else {
                List<AdResourceStats> adimagesList = JSON.parseArray(groupByImageHashResult.get("adResourceStatsList").toString(), AdResourceStats.class);
                // 封装响应结果
                data = new HashMap<>();
                Set<String> imageHashSet = new HashSet<>();
                for (AdResourceStats adResourceStats : adimagesList) {
                    imageHashSet.add(adResourceStats.getImageHash());
                }
                final Map<String, Integer> activeAdCountMap = adImageService.groupByImageHashForActiveAdCount(imageHashSet, user);

                final List<User> all = userService.findAll();

                List<Map> transform = Lists.transform(adimagesList, new Function<AdResourceStats, Map>() {
                    @Override
                    public Map apply(AdResourceStats adResourceStats) {
                        return adResourceStatsToMap(adResourceStats, all, activeAdCountMap);
                    }
                });
                data.put("resources", transform);
                data.put("summary", groupByImageHashResult.get("summary"));
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 第三方图片-根据条件查询图片列表
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getReviewAdimageList")
    @ResponseBody
    public ResponseEntity<String> getReviewAdimageList(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {

            AdimageTagParam adimageTagParam = JSON.parseObject(param, AdimageTagParam.class);
            User user = (User) request.getSession().getAttribute("user");

            if (adimageTagParam.getPSize() == null) {
                adimageTagParam.setPSize(CommonConstants.DEFAULT_PAGE_SIZE_100);
            }

            if (adimageTagParam.getCPage() == null) {
                adimageTagParam.setCPage(1);
            }

            //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
            changeAdResourceTagParams(adimageTagParam, user);
            Map<String, Object> groupByImageHashResult = adImageService.getAdimagesList(adimageTagParam, user);
            if (null == groupByImageHashResult || null == groupByImageHashResult.get("adResourceStatsList")) {
                data = new HashMap<>();
                data.put("resources", "");
            } else {
                List<AdResourceStats> adimagesList = JSON.parseArray(groupByImageHashResult.get("adResourceStatsList").toString(), AdResourceStats.class);
                adImageService.updatePageView(adimagesList);
                // 封装响应结果
                data = new HashMap<>();
                Set<String> imageHashSet = new HashSet<>();
                for (AdResourceStats adResourceStats : adimagesList) {
                    imageHashSet.add(adResourceStats.getImageHash());
                }
                final Map<String, Integer> activeAdCountMap = adImageService.groupByImageHashForActiveAdCount(imageHashSet, user);

                final List<User> all = userService.findAll();

                List<Map> transform = Lists.transform(adimagesList, new Function<AdResourceStats, Map>() {
                    @Override
                    public Map apply(AdResourceStats adResourceStats) {
                        return adResourceStatsToMapForReview(adResourceStats, all, activeAdCountMap);
                    }
                });
                data.put("resources", transform);
                data.put("summary", groupByImageHashResult.get("summary"));
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     *  查询素材参数修改
     *  @param adResourceQueryParam
     * @param user
     */
    private void changeAdResourceTagParams(AdResourceQueryParam adResourceQueryParam, User user) {
        List<Long> roleIds = userService.getRoleByUser(user.getId());
        //外部美宣查询只能查询自己的
        if (ListUtil.isNotEmpty(roleIds) && roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER)) {
            adResourceQueryParam.setIsMy(true);
        }

        if (!adResourceQueryParam.isReview()) {
            //不是我的图片的话 查询别人的图片
            if (!adResourceQueryParam.isMy()) {
                Set<String> userIdSet = Sets.newHashSet();
                List<User> orgId = userService.findByOrgId(user.getOrgId());
                for (User user1 : orgId) {
                    userIdSet.add(user1.getTicket());
                }
                userIdSet.remove(user.getTicket());
                adResourceQueryParam.setUserIdSet(userIdSet);

                //只要appname为空 就必须过滤应用 应用权限
                if (ListUtil.isEmpty(adResourceQueryParam.getAppNames())) {
                    addApps(adResourceQueryParam, user, roleIds);
                }
            } else {
                adResourceQueryParam.setUserIdSet(Sets.newHashSet(user.getTicket()));
            }
        } else {
            //审核可以审核自己有权限的所有应用的图片
            //只要appname为空 就必须过滤应用 应用权限
            if (ListUtil.isEmpty(adResourceQueryParam.getAppNames())) {
                addApps(adResourceQueryParam, user, roleIds);
            }
        }
    }

    /**
     * //只要appname为空 就必须过滤应用
     *
     * @param adResourceQueryParam
     * @param user
     * @param roleIds
     */
    private void addApps(AdResourceQueryParam adResourceQueryParam, User user, List<Long> roleIds) {
        // 如果是
        List<ConnectionObject> connectionObjectBoList;
        if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
            //设计者获取公司下全部有权限的应用
            connectionObjectBoList = connectionObjectService.findByOrgIdAndType(user.getOrgId(), ConnectionObjectType.Application.getType());
        } else {
            //非设计者获取各自有权限的应用
            connectionObjectBoList = connectionObjectService.findByUserIdAndType(user.getTicket(), ConnectionObjectType.Application.getType());
        }

        List<String> appsList = new ArrayList<>();
        for (int i = 0; i < connectionObjectBoList.size(); i++) {
            ConnectionObject connectionObjectBo = connectionObjectBoList.get(i);
            appsList.add(connectionObjectBo.getName());
        }
        //外链
        List<ProductManage> productManages = productManageRdbService.findByOrgId(user.getOrgId());
        if (!CollectionUtils.isEmpty(productManages)){
            for (ProductManage productManage : productManages){
                if (!appsList.contains(productManage.getProdName())){
                    appsList.add(productManage.getProdName());
                }
            }
        }
        adResourceQueryParam.setAppNames(appsList);
    }


    /**
     * 查询图片的细分数据
     */
    @RequestMapping(value = "getAdgroupStatsByBreakdowns")
    @ResponseBody
    public ResponseEntity<String> getAdResourceStatsByBreakdowns(
            @RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("AdGroupStatsController getAdResourceStatsByBreakdowns() begin.");
        try {
            AdResourceStatsParam adResourceStatsParam = JSON.parseObject(param, AdResourceStatsParam.class);
            String imageHash = adResourceStatsParam.getImageHash();
            String breakdowns = adResourceStatsParam.getBreakdowns();
            Integer days = adResourceStatsParam.getDays();
            if (StringUtils.isEmpty(breakdowns) || null == days) {
                OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.PARAM_EXCEPTION, null);
                return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
            }
            List<AdResourceStats> adResourceStatses;
            // 由于新图片还没有ImageHash，因此直接返回空列表
            if (StringUtils.isEmpty(imageHash)) {
                adResourceStatses = new ArrayList<>();
            } else {
                User user = (User) request.getSession().getAttribute("user");
                adResourceStatsParam.setOrgId(user.getOrgId());
                // 从Mongodb中按天查询
                adResourceStatses = adResourceService.getImageStatsGroupByBreakdowns(adResourceStatsParam);
            }
            OutputResult outputResult = ResponseUtils.bulidOutputResult(null, adResourceStatses);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error("AdGroupStatsController getAdResourceStatsByBreakdowns() error" + e.getMessage(), e);
        } finally {
            logger.info("AdGroupStatsController getAdResourceStatsByBreakdowns() end.");
        }
        // 异常返回
        OutputResult outputResult = ResponseUtils.bulidOutputResult(ErrorType.BUSINESS_EXCEPTION, null);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 广告发布查询全量图片
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getAdimagesAllListMon")
    @ResponseBody
    public ResponseEntity<String> getAdimagesAllListMon(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
//        Map<String, Object> data = null;
        List<Map> transform = null;
        try {
            AdimageTagParam adimageTagParam = JSON.parseObject(param, AdimageTagParam.class);
            User user = (User) request.getSession().getAttribute("user");
            //不用翻页
            adimageTagParam.setCPage(0);
            if (ListUtil.isEmpty(adimageTagParam.getAppNames())) {
                //只要appname为空 就必须过滤应用 应用权限
                List<Long> roleIds = userService.getRoleByUser(user.getId());
                addApps(adimageTagParam, user, roleIds);
            }

            //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
            final List<User> all = userService.findAll();
            for (User user1 : all) {
                if (user1.getOrgId().longValue() == user.getOrgId()) {
                    adimageTagParam.getUserIdSet().add(user1.getTicket());
                }
            }

            Map<String, Object> groupByImageHashResult = adImageService.getAdimagesList(adimageTagParam, user);
            if (null != groupByImageHashResult && null != groupByImageHashResult.get("adResourceStatsList")) {
                List<AdResourceStats> adimagesList = JSON.parseArray(groupByImageHashResult.get("adResourceStatsList").toString(), AdResourceStats.class);
                transform = Lists.transform(adimagesList, new Function<AdResourceStats, Map>() {
                    @Override
                    public Map apply(AdResourceStats adResourceStats) {
                        return adResourceStatsToMap(adResourceStats, all, null);
                    }
                });
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, transform);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 图片上传消息通知
     * @param param
     * @return
     */
    @RequestMapping(value = "getAdimagesAllListMonByimageBathId")
    @ResponseBody
    public ResponseEntity<String> getAdimagesAllListMonByimageBathId(@RequestParam(value = "param", required = true) String param) {
        ErrorType errorType = null;
        List<Map> transform = null;
        try {
            JSONObject jsonObject = JSON.parseObject(param);
            String imageBathId = jsonObject.getString("imageBathId");

            List<AdResourceStats> adimagesList = adImageService.getAdimagesAllListMonByimageBathId(imageBathId);

            transform = Lists.transform(adimagesList, new Function<AdResourceStats, Map>() {
                @Override
                public Map apply(AdResourceStats adResourceStats) {
                    return adResourceStatsToMap(adResourceStats, null, null);
                }
            });
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, transform);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 上传图片
     * @param request
     * @return
     */
    @RequestMapping("uploadImg")
    @ResponseBody
    public ResponseEntity<String> uploadImg(HttpServletRequest request) {
        ErrorType errorType = null;
        List<UploadAdimageBoResult> data = null;
        try {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获得上传文件列表
            List<MultipartFile> fileList = multiRequest.getFiles("files");
            String appName = request.getParameter("appName");
            String appId = request.getParameter("appId");

            if (CollectionUtils.isEmpty(fileList)) {
                errorType = ErrorType.UPLOAD_RESOURCE_FAIL;
            } else if (StringUtils.isEmpty(appName)) {
                errorType = ErrorType.ADRESOURCE_PARAMS_NO_CHECKED_APP_ERROR;
            } else if (StringUtils.isEmpty(appId)) {
                errorType = ErrorType.ADRESOURCE_PARAMS_NO_CHECKED_APP_ERROR;
            } else {
                User user = (User) multiRequest.getSession().getAttribute("user");
                // 上传的所有图片名称
//                String[] fileNames = request.getParameterValues("fileNames");
//                String fbConnectionObjectIdStr = request.getParameter("fbConnectionObjectId");

                data = adResourceService.uploadAdImage(fileList, request.getRealPath("/"), appId, appName, user);
                if (null == data) {
                    errorType = ErrorType.UPLOAD_RESOURCE_FAIL;
                }
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 图片打标签：显示初始化标签
     * @param param
     * @return
     */
    @RequestMapping("showInitTags")
    @ResponseBody
    public ResponseEntity<String> showInitTags(@RequestParam(value = "param", required = true) String param) {
        OutputResult outputResult = null;
        ErrorType errorType = null;
        Map<String, Object> data = Maps.newHashMap();
        try {
            AdimageInitParam adimageInitParam = JSON.parseObject(param, AdimageInitParam.class);
            String appName = adimageInitParam.getAppName();
            if (StringUtils.isNotEmpty(appName)) {
                data.put("appNames", Sets.newHashSet(appName));
            }

            //会先图片
            String mongodbIds = adimageInitParam.getMongodbIds();
            if (StringUtils.isNoneBlank(mongodbIds)) {
                List<String> strings = Splitter.on("|").omitEmptyStrings().splitToList(mongodbIds);
                if (strings.size() > 0) {
                    List<AdResourceStats> adResourceStats = adResourceService.findByMongodbIds(strings);


                    //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
                    final List<User> all = userService.findAll();
                    List<Map> transform = Lists.transform(adResourceStats, new Function<AdResourceStats, Map>() {
                        @Override
                        public Map apply(AdResourceStats adResourceStats) {
                            return adResourceStatsToMap(adResourceStats, all, null);
                        }
                    });
                    data.put("adimgages", transform);
                }
            }
            data.put("param", param);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 保存图片评论
     * @param param
     * @param request
     * @return
     */
    @RequestMapping("saveComment")
    @ResponseBody
    public ResponseEntity<String> saveComment(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            AdResourceCommentParam adResourceCommentParam = JSON.parseObject(param, AdResourceCommentParam.class);
            if (adResourceCommentParam != null) {
                AdResourceComment adResourceComment = new AdResourceComment();
                adResourceComment.setUsername(StringUtil.isEmpty(user.getUsername()) ? user.getNickname() : user.getUsername());
                adResourceComment.setCommentBody(adResourceCommentParam.getCommentBody());
                adResourceComment.setCommentDate(new Date().getTime());
                adResourceService.saveAdImageComment(adResourceCommentParam.getMongodbId(), adResourceComment);
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 更新图片信息
     * @param param
     * @param request
     * @return
     */
    @RequestMapping("saveImgTags")
    @ResponseBody
    public ResponseEntity<String> saveImgTags(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        Map<String, Object> data = Maps.newHashMap();
        try {
            User user = (User) request.getSession().getAttribute("user");
            List<AdimageTagParam> adimageTagParamList = JSON.parseArray(param, AdimageTagParam.class);
            List<AdResourceStats> mongodbIds = new ArrayList();
            AdResourceStats stats;
            for (AdimageTagParam adimageTagParam : adimageTagParamList) {
                String mongodbId = adimageTagParam.getMongodbId();
                List<String> appNamesParams = adimageTagParam.getAppNames();


                String fileName = adimageTagParam.getFileName();
                List<String> countries = adimageTagParam.getCountries();
                String gender = adimageTagParam.getGender();
                List<String> interests = adimageTagParam.getInterests();
                List<String> languages = adimageTagParam.getLanguages();

                stats = new AdResourceStats();
                stats.setMongodbId(mongodbId);
                stats.setReviewer(StringUtil.isEmpty(user.getNickname()) ? user.getUsername() : user.getNickname());
                stats.setReviewTime(new Date());
                //如果是审核调用，需要锁定，不能多人同时审核同一张图
                if (adimageTagParam != null && adimageTagParam.getReviewStatus() != null && adimageTagParam.getReviewStatus() == 1) {
                    String key = "review_picture_" + mongodbId;
                    if (redisClient.hasKey(key)) {
                        errorType = ErrorType.PUBLISH_CONDITION_FLAG;
                    } else {
                        try {
                            redisClient.set(key, 1);
                            adResourceService.saveAdimageTag(mongodbId, fileName, appNamesParams, countries, languages, gender, interests, user, adimageTagParam.getReviewStatus());

                            mongodbIds.add(stats);
                        } catch (Exception e) {
                            errorType = ErrorType.PUBLISH_CONDITION_FAIL;
                            logger.error("AdPublishConditionController saveImgTags() 审核 多人操作Error", e);
                        } finally {
                            redisClient.delete(key);
                        }
                    }
                } else {
                    List<ConnectionObject> connectionObjectBoList;
                    List<Long> roleIds = userService.getRoleByUser(user.getId());
                    if (ListUtil.isNotEmpty(roleIds) && (roleIds.contains(CommonConstants.ROLE_UIDESIGNER) || roleIds.contains(CommonConstants.ROLE_OUTERUIDESIGNER))) {
                        //如果是美宣，则查询该公司下全部的有权限的应用
                        connectionObjectBoList = connectionObjectService.findByOrgIdAndType(user.getOrgId(), ConnectionObjectType.Application.getType());
                    } else {
                        //非美宣，查询各自有权限的应用
                        connectionObjectBoList = connectionObjectService.findByUserIdAndType(user.getTicket(), ConnectionObjectType.Application.getType());
                    }


                    List<String> appsList = new ArrayList<>();
                    if (connectionObjectBoList != null) {
                        for (int i = 0; i < connectionObjectBoList.size(); i++) {
                            ConnectionObject connectionObjectBo = connectionObjectBoList.get(i);
                            appsList.add(connectionObjectBo.getName());
                        }
                    }

                    //外链
                    List<ProductManage> productManages = productManageRdbService.findByOrgId(user.getOrgId());
                    if (!CollectionUtils.isEmpty(productManages)){
                        for (ProductManage productManage : productManages){
                            if (!appsList.contains(productManage.getProdName())){
                                appsList.add(productManage.getProdName());
                            }
                        }
                    }

                    List<String> appNames = AnalysisAppNames(appNamesParams, appsList, mongodbId);
                    adResourceService.saveAdimageTag(mongodbId, fileName, appNames, countries, languages, gender, interests, user, adimageTagParam.getReviewStatus());
                    mongodbIds.add(stats);
                }
            }
            data.put("ok", "ok");
            data.put("results", mongodbIds.toArray(new AdResourceStats[mongodbIds.size()]));
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 分析app名称Tag是否修改
     *
     * @param appNamesParams
     * @return
     */
    private List<String> AnalysisAppNames(List<String> appNamesParams, List<String> dbAppNames, String mongodbId) {

        AdResourceStats adResourceStats = adResourceService.findByMongodbId(mongodbId);
        List<Object> application = adResourceStats.getTags().get("application");
        List<String> mongdbAppNames = new ArrayList<>();
        if (ListUtil.isNotEmpty(application)) {
            for (Object o : application) {
                mongdbAppNames.add(o.toString());
            }
        }

        {
            for (String dbAppName : dbAppNames) {
                mongdbAppNames.remove(dbAppName);
            }
            mongdbAppNames.addAll(appNamesParams);
        }
        return mongdbAppNames;
    }


    /**
     * 上传视频
     * @param request
     * @return
     */
    @RequestMapping("uploadAdvideo")
    @ResponseBody
    public ResponseEntity<String> uploadAdvideo(HttpServletRequest request) {
        ErrorType errorType = null;
        List<AdVideoBo> data = null;
        try {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获得上传文件列表
            List<MultipartFile> fileList = multiRequest.getFiles("files");
            String appName = request.getParameter("appName");
            ArrayList appNames = Lists.newArrayList(appName);
            String appId = request.getParameter("appId");

            if (CollectionUtils.isEmpty(fileList)) {
                errorType = ErrorType.UPLOAD_RESOURCE_FAIL;
            } else if (CollectionUtils.isEmpty(appNames)) {
                errorType = ErrorType.ADRESOURCE_PARAMS_NO_CHECKED_APP_ERROR;
            } else {
                User user = (User) multiRequest.getSession().getAttribute("user");
                data = adVideoService.uploadAdvideo(appNames, appId, fileList, user, request.getRealPath("/"));
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 更新视频
     * @param param
     * @param request
     * @return
     */
    @RequestMapping("updateAdvideos")
    @ResponseBody
    public ResponseEntity<String> updateAdvideos(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        try {
            List<AdResourceUpdateParam> adResourceUpdateParams = JSON.parseArray(param, AdResourceUpdateParam.class);
            User user = (User) request.getSession().getAttribute("user");
            adVideoService.updateAdvideos(adResourceUpdateParams, user);
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, null);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 获取单个视频
     * @param param
     * @return
     */
    @RequestMapping(value = "getAdvideoByIds")
    @ResponseBody
    public ResponseEntity<String> getAdvideoByIds(@RequestParam(value = "param", required = true) String param) {
        ErrorType errorType = null;
        List<AdVideoBo> data = null;
        try {
            AdResourceQueryParam adResourceQueryParam = JSON.parseObject(param, AdResourceQueryParam.class);
            data = adVideoService.getAdvideoByIds(adResourceQueryParam.getMongodbIds());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 视频管理获取视频列表
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getAdvideosList")
    @ResponseBody
    public ResponseEntity<String> getAdvideoesList(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        Map data = null;
        try {

            AdResourceQueryParam adResourceQueryParam = JSON.parseObject(param, AdResourceQueryParam.class);
            User user = (User) request.getSession().getAttribute("user");

            //赋值默认分页信息
            if (adResourceQueryParam.getPSize() == null) {
                adResourceQueryParam.setPSize(CommonConstants.DEFAULT_PAGE_SIZE_100);
            }
            if (adResourceQueryParam.getCPage() == null) {
                adResourceQueryParam.setCPage(1);
            }

            //外部美宣查询只能查询自己的, 增加有权限的应用
            changeAdResourceTagParams(adResourceQueryParam, user);

            Map<String, Object> groupByImageHashResult = adVideoService.getAdvideosList(adResourceQueryParam, user);
            if (null == groupByImageHashResult || null == groupByImageHashResult.get("adVideoList")) {
                data = new HashMap<>();
            } else {
                data = groupByImageHashResult;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 广告发布获取视频列表
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "getAdvideosAllList")
    @ResponseBody
    public ResponseEntity<String> getAdvideosAllList(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        ErrorType errorType = null;
        List<AdVideoBo> data = null;
        try {

            AdResourceQueryParam adResourceQueryParam = JSON.parseObject(param, AdResourceQueryParam.class);
            User user = (User) request.getSession().getAttribute("user");

            if (ListUtil.isEmpty(adResourceQueryParam.getAppNames())) {
                //只要appname为空 就必须过滤应用 应用权限
                List<Long> roleIds = userService.getRoleByUser(user.getId());
                addApps(adResourceQueryParam, user, roleIds);
            }

            //暂时先将AdimageTagParam作为参数传递到service层，等稳定调整
            Map<String, Object> groupByImageHashResult = adVideoService.getAdvideosList(adResourceQueryParam, user);
            if (null == groupByImageHashResult || null == groupByImageHashResult.get("adVideoList")) {
                data = new ArrayList<>();
            } else {
                data = (List<AdVideoBo>) groupByImageHashResult.get("adVideoList");
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error(e.getMessage(), e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
